from sqlalchemy import or_
from app import db
from app.models.admin import Admin
from app.models.role import Role
from app.models.department import Department


class AdminService:
    """管理员服务层"""
    
    @staticmethod
    def get_list(page=1, per_page=10, keyword=None, status=None):
        """获取管理员列表"""
        query = Admin.query
        
        # 关键词搜索
        if keyword:
            query = query.filter(or_(
                Admin.admin_name.like(f'%{keyword}%'),
                Admin.username.like(f'%{keyword}%')
            ))
        
        # 状态筛选
        if status is not None:
            query = query.filter(Admin.status == status)
        
        # 按创建时间降序排列
        query = query.order_by(Admin.create_time.desc())
        
        return query, page, per_page
    
    @staticmethod
    def get_by_id(admin_id):
        """根据ID获取管理员"""
        return Admin.query.get(admin_id)
    
    @staticmethod
    def get_by_username(username):
        """根据用户名获取管理员"""
        return Admin.query.filter_by(username=username).first()
    
    @staticmethod
    def create(data):
        """创建管理员"""
        admin = Admin()
        admin.admin_name = data.get('admin_name')
        admin.username = data.get('username')
        admin.set_password(data.get('password'))
        admin.role_id = data.get('role_id')
        admin.department_id = data.get('department_id')
        admin.status = data.get('status', True)
        
        db.session.add(admin)
        db.session.commit()
        return admin
    
    @staticmethod
    def update(admin_id, data):
        """更新管理员"""
        admin = Admin.query.get(admin_id)
        if not admin:
            return None
        
        admin.admin_name = data.get('admin_name', admin.admin_name)
        admin.role_id = data.get('role_id', admin.role_id)
        admin.department_id = data.get('department_id', admin.department_id)
        admin.status = data.get('status', admin.status)
        
        # 如果提供了新密码，则更新密码
        if data.get('password'):
            admin.set_password(data.get('password'))
        
        db.session.commit()
        return admin
    
    @staticmethod
    def delete(admin_id):
        """删除管理员"""
        admin = Admin.query.get(admin_id)
        if not admin:
            return False
        
        db.session.delete(admin)
        db.session.commit()
        return True
    
    @staticmethod
    def get_role_options():
        """获取角色选项"""
        roles = Role.query.filter_by(status=True).all()
        return [{'id': role.id, 'name': role.name} for role in roles]
    
    @staticmethod
    def get_department_options():
        """获取部门选项"""
        departments = Department.query.filter_by(status=True).all()
        return [{'id': dept.id, 'name': dept.name} for dept in departments] 